import axios from 'axios'
import { Dialog } from 'vant'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000,
  withCredentials: false
})

service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('userToken')
    if (token) config.headers.authorization = `Bearer ${token}`
    return config
  },
  error => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    if (response && response.data) {
      if (response.data.code === 401) {
        Dialog.alert({
          title: '提示',
          message: '登录已过期，请重新登录',
          theme: 'round-button',
          confirmButtonColor: '#1989FA'
        }).then(() => {
          localStorage.removeItem('userToken')
          location.href = location.href
        })
      }
      return response.data
    } else {
      return response
    }
  },
  error => {
    return Promise.reject(error)
  }
)

/**
 * @description: 请求方法
 * @param {String} type       请求类型
 * @param {String} url        api接口地址
 * @param {any}    data       参数
 */
const HR = (type, url, data = null) => {
  type = type ? type.toUpperCase() : 'GET'
  if (!url) return

  if (type == 'GET') return service.get(url, { params: data })
  if (type == 'POST') return service.post(url, data)
  if (type == 'PUT') return service.put(url, data)
}

export default HR
